package com.leyou.auth.task;


import com.leyou.auth.config.JwtProperties;
import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.utils.JwtUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Component
@Data
@EnableConfigurationProperties(JwtProperties.class)
@Slf4j
public class PrivilegeTokenHolder {

    private String token;


    @Autowired
    private JwtProperties prop;

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;

    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    public void loadToken() throws InterruptedException {
        while (true){
            try {
                // 向ly-auth发起请求，获取JWT
                AppInfo appInfo = new AppInfo();
                appInfo.setId(prop.getApp().getId());
                appInfo.setServiceName(prop.getApp().getSecret());
                this.token = JwtUtils.generateTokenExpireInMinutes(appInfo, prop.getPrivateKey(), prop.getApp().getExpire());
                log.info("【网关】定时获取token成功");
                break;
            } catch (Exception e) {
                log.error("【网关】定时获取token失败");
            }
            Thread.sleep(100000L);
        }

    }
    public String getToken() {
        return token;
    }

}
